//
//  WTLiveView.m
//  WTLiveSDKDemo
//
//  Created by ben on 2016/11/30.
//  Copyright © 2016年 ben. All rights reserved.
//

#import "WTLiveView.h"
#import "LFLiveKit.h"
#import "KLCPopup.h"
#import "WTVideoView.h"
#import "WTLiveCreateService.h"
#import "WTRobotGetService.h"
#import "WTLiveAddPersonNumService.h"
#import "WTLiveSDK.h"
#import "WTCategories.h"
#import "WTCloseLiveService.h"
#import "WTLivePreService.h"
#import "WTCloseLiveService.h"

#import "WTBeautySilerView.h"


@interface WTLiveView ()<WTVideoViewDelegate>
@property (nonatomic,strong) LFLiveSession* session;
@property (nonatomic,strong) WTVideoView*   videoView;
@property (nonatomic,strong) WTLiveCreateService*   liveCreateService;
@property (nonatomic,strong) WTRobotGetService*     robotGetService;
@property (nonatomic,strong) WTCloseLiveService*     closeLiveService;
@property (nonatomic,strong) WTLivePreService*       livePreService;
@property (nonatomic,strong) WTLiveAddPersonNumService*     addPersonNumService;
@property (nonatomic,assign) NSInteger      vertify_id;
@property (nonatomic,strong) WTBeautySilerView* beautySilerView;
@end

@implementation WTLiveView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        [self.session setRunning:YES];
        
        [self addSubview:self.videoView];
        [self.videoView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(self);
        }];
        
        __weak __typeof(self)weakSelf = self;
        [self.videoView.liveExtendView.backButton addAction:^{
            
            if(weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(liveViewCloseLive:statusColse:)]){
                [weakSelf.delegate liveViewCloseLive:weakSelf statusColse:YES];
            }
        }];
        
        [self addListenerForNotificationName:UIApplicationDidEnterBackgroundNotification handler:^(NSString *notificationName, NSDictionary *userInfo) {
            [[WTLiveSDK shareSDK].chatRoomManager sendAnchorLeave];
        }];
        
        [self addListenerForNotificationName:UIApplicationWillEnterForegroundNotification handler:^(NSString *notificationName, NSDictionary *userInfo) {
            [[WTLiveSDK shareSDK].chatRoomManager sendAnchorEnter];
        }];
        
        [self addListenerForNotificationName:UIApplicationWillTerminateNotification handler:^(NSString *notificationName, NSDictionary *userInfo) {
            [[WTLiveSDK shareSDK].chatRoomManager stopLive];
        }];
    }
    return self;
}

- (void)start{
    
    [self showGifLoding];
    __weak __typeof(self)weakSelf = self;
    NSMutableDictionary* params = [self.params mutableCopy];
    [params addEntriesFromDictionary:@{@"session_token":WTConfig.session_token}];
    [self.liveCreateService start:params completionHandler:^(id responseObject, NSError *error) {
        if(!error){
            WTLiveCreateModel* model = responseObject;
            [weakSelf beginLive:model];
        }else {
            [weakSelf hideGifLoding];
        }
    }];
}

- (void)startApplyLive{

    __weak __typeof(self)weakSelf = self;
    
    NSMutableDictionary* params =  [self.params mutableCopy];
    [params addEntriesFromDictionary:@{@"session_token":WTConfig.session_token}];
    [self.livePreService start:@{@"session_token":WTConfig.session_token} completionHandler:^(id responseObject, NSError *error) {

        NSInteger screening_id = [responseObject integerValue];
        if(screening_id > 0){
            params[@"id"] = @(screening_id);
            [self.liveCreateService start:params completionHandler:^(id responseObject, NSError *error) {
                if(!error){
                    WTLiveCreateModel* model = responseObject;
                    [weakSelf beginLive:model];
                }
            }];
        }
    }];
}

- (void)stop{
    
    [self.session stopLive]; //关闭推流
    [[WTLiveSDK shareSDK].chatRoomManager stopLive]; //发送直播结束的消息
    [self.videoView clearGiftAnimationCaches]; //清除礼物动画的缓存
    
    //向服务器发出关闭直播间的请求
    [self.closeLiveService start:@{@"session_token":WTConfig.session_token} completionHandler:^(id responseObject, NSError *error) {
        
        //[[NSNotificationCenter defaultCenter] postNotificationName:K_WX_CloseLiveNotification object:nil];
        
    }];
}


#pragma mark private methods
- (void)beginLive:(WTLiveCreateModel*)model{
    
    //赋值房间ID
    self.videoView.roomId = [model.livecreate_chatroom_id integerValue];
    
    //设置房间的ID
    [[WTLiveSDK shareSDK].chatRoomManager setRoomID:[NSString stringWithFormat:@"%zd",[model.livecreate_chatroom_id integerValue]]];
    
    //给房间添加主播信息
    self.videoView.liveExtendView.personInfoView.avatar = WTConfig.avatar;
    self.videoView.liveExtendView.personInfoView.nick = WTConfig.nick;
    self.videoView.liveExtendView.coinView.coinCount = [NSString stringWithFormat:@"%lld",[model.livecreate_income_total longLongValue]];
    self.videoView.liveExtendView.accountView.cuteCode = WTConfig.cuteCode;
    
    //开始推流
    [self startPushStream:model.livecreate_push_url];
    
    //私信页面
    WTPrivateMessageAnchorModel* privateMessageAnchorModel = [[WTPrivateMessageAnchorModel alloc] init];
    privateMessageAnchorModel.anchor_name = WTConfig.nick;
    privateMessageAnchorModel.anchor_avatar = WTConfig.avatar;
    privateMessageAnchorModel.anchor_level = WTConfig.level;
    privateMessageAnchorModel.anchor_net_ease = WTConfig.net_accid;
    privateMessageAnchorModel.anchor_user_id = WTConfig.user_id;
    self.videoView.privateMessageView.anchor_info_model = privateMessageAnchorModel;
    self.videoView.privateMessageView.is_live = YES;
    [self.videoView.privateMessageView update];
    
    
    __weak __typeof(self)weakSelf = self;
    //进入房间
    [[WTLiveSDK shareSDK].chatRoomManager enterChatroom:^(BOOL isEnter, NSInteger status) {
        if(isEnter){
            if(status == 1){
                
                //进入房间成功 显示相关的view
                weakSelf.videoView.alpha = 1;
                
                //添加机器人
                [weakSelf.robotGetService start:@{@"session_token":WTConfig.session_token,@"room_id":model.livecreate_chatroom_id} completionHandler:^(id responseObject, NSError *error) {
                    
                }];
                
                //上传直播间的人数
                [NSTimer scheduledTimerWithAutoTimeInterval:30 target:self block:^(NSTimer *timer) {
                    
                    [[WTLiveSDK shareSDK].chatRoomManager fetchChatRoomPersonCount:[NSString stringWithFormat:@"%zd",[model.livecreate_chatroom_id integerValue]] completion:^(NSInteger onlinePersonCount) {
                        
                        [weakSelf.addPersonNumService start:@{@"session_token":WTConfig.session_token,@"num":@(onlinePersonCount)} completionHandler:^(id responseObject, NSError *error) {
                            
                        }];
                    }];
                    
                } userInfo:nil repeats:YES];
                
                [weakSelf hideGifLoding];
            }else {
                [weakSelf showTip:@"创建直播失败，请重试" completion:^{
                    if(weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(liveViewCloseLive:statusColse:)]){
                        [weakSelf.delegate liveViewCloseLive:weakSelf statusColse:NO];
                    }
                }];
            }
        }
    }];
}


#pragma mark getter
- (LFLiveSession*)session {
    if (!_session) {
        _session = [[LFLiveSession alloc] initWithAudioConfiguration:[LFLiveAudioConfiguration defaultConfiguration] videoConfiguration:[LFLiveVideoConfiguration defaultConfiguration]];
        _session.preView = self;
    }
    return _session;
}

- (WTVideoView *)videoView{
    if(!_videoView){
        _videoView = [[WTVideoView alloc] init];
        _videoView.alpha = 0;
        _videoView.delegate = self;
        _videoView.playToolView.isLivePage = YES;
    }
    return _videoView;
}

- (WTBeautySilerView *)beautySilerView{
    if(!_beautySilerView){
        _beautySilerView = [[[NSBundle mainBundle] loadNibNamed:@"WTBeautySilerView" owner:self options:nil] lastObject];
        _beautySilerView.height = 200;
        _beautySilerView.width = [UIScreen screenWidth];
    }
    return _beautySilerView;
}

- (WTLiveCreateService *)liveCreateService{
    if(!_liveCreateService){
        _liveCreateService = [[WTLiveCreateService alloc] init];
    }
    return _liveCreateService;
}

- (WTRobotGetService *)robotGetService{
    if(!_robotGetService){
        _robotGetService = [[WTRobotGetService alloc] init];
    }
    return _robotGetService;
}

- (WTLiveAddPersonNumService *)addPersonNumService{
    if(!_addPersonNumService){
        _addPersonNumService = [[WTLiveAddPersonNumService alloc] init];
    }
    return _addPersonNumService;
}

- (WTCloseLiveService *)closeLiveService{
    if(!_closeLiveService){
        _closeLiveService = [[WTCloseLiveService alloc] init];
    }
    return _closeLiveService;
}

- (WTLivePreService *)livePreService{
    if(!_livePreService){
        _livePreService = [[WTLivePreService alloc] init];
    }
    return _livePreService;
}

- (void)startPushStream:(NSString*)pushURL{
    LFLiveStreamInfo *streamInfo = [LFLiveStreamInfo new];
    streamInfo.url = pushURL;
    [self.session startLive:streamInfo];
}

#pragma mark WTVideoViewDelegate
- (void)videoViewChangeCamera:(WTVideoView *)view{
    
    AVCaptureDevicePosition captureDevicePosition = self.session.captureDevicePosition;
    self.session.captureDevicePosition = (captureDevicePosition == AVCaptureDevicePositionBack) ? AVCaptureDevicePositionFront : AVCaptureDevicePositionBack;
}

- (void)videoViewGiftDetail:(WTVideoView *)view{
    
    if(self.delegate && [self.delegate respondsToSelector:@selector(liveViewGoGiftDetail:)]){
        [self.delegate liveViewGoGiftDetail:self];
    }
}
@end
